package com.wbs.controller;


import com.alibaba.fastjson.JSONObject;
import com.wbs.api.RocketMQAPI;
import com.wbs.model.TbUser;
import com.wbs.resutil.Result;
import com.wbs.resutil.ResultEnums;
import com.wbs.service.LoginService;
import com.wbs.utils.JwtUtil;
import com.wbs.vo.UserTokenVO;
import com.wbs.vo.UserVO;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @Author: 芝梦
 * @Description: 登陆与注册控制层
 * @DateTime: 2024/2/22 21:09
 */
@RequestMapping("login")
@RestController
public class LoginController {
    @Autowired
    private RocketMQAPI rocketMQAPI;

    @Autowired
    private LoginService loginService;

    @Autowired
    private JwtUtil jwtUtil;

    //登陆
    @PostMapping("login")
    public Result login(@RequestParam String username, @RequestParam String password){
        //1. 获取subject
        Subject subject = SecurityUtils.getSubject();
        //2. 封装token
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        //3. 调用login方法
        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
            return Result.RESPONSE(ResultEnums.USERNAME_AND_PASSWORD_ERROR);
        } catch (IncorrectCredentialsException e){
            return Result.RESPONSE(ResultEnums.USERNAME_AND_PASSWORD_ERROR);
        }
        //获取当前用户
        TbUser tbUser = (TbUser) subject.getPrincipal();
        //脱敏处理
        UserTokenVO userTokenVO = new UserTokenVO();
        BeanUtils.copyProperties(tbUser,userTokenVO);
        //生成token
        String token1 = jwtUtil.createJwt(userTokenVO.getId().toString(), JSONObject.toJSONString(userTokenVO), "userRoles");

        return Result.SUCCESS().setData(token1);
    }

    @GetMapping("message")
    public Result message(@RequestParam String number){
        rocketMQAPI.sendMessage(number);
        return Result.SUCCESS();
    }

    @GetMapping("test")
    public void test(String number){
        System.err.println(number);
    }

    //注册
    @PostMapping("register")
    public Result register(@RequestBody UserVO userVO){
        return loginService.register(userVO);
    }


}
